#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
  pid_t id = fork();
  if(id == 0){
    int cnt = 5;
    while(cnt--){
      printf("child[%d] is running; cnt is : %d\n",getpid(), cnt);
      sleep(1);
    }
    exit(0);
  }
 // int status = 0;
 // while(1){
 //   pid_t ret = waitpid(id, &status, WNOHANG);
 //   if(ret == 0){//子进程没有退出，但是waitpid等待是成功的，需要父进程重复进行等待
 //     printf("Do father things\n");
 //   }
 //   else if(ret > 0){//子进程退出了，waitpid也成功了，获取到了对应的结果
 //     printf("father wait: %d. success,status exit code:%d, status signal:%d\n",ret,(status>>8)&0xFF,status&0x7F);
 //     break;
 //   }
 //   else{//等待失败
 //     perror("waitpid\n");
 //     break;
 //   }
 //   sleep(1);
 // }
  sleep(10); 
  printf("father wait begin!\n");
  //pid_t ret = wait(NULL);   
  
  //pid_t ret = waitpid(id, NULL,0); // 等待指定一个进程
  //pid_t ret = waitpid(-1, NULL,0); // 等待任意一个进程，等价于wait
  
  int status = 0;
  pid_t ret = waitpid(id, &status,0); //0：默认行为，阻塞等待。WNOHANG：非阻塞等待
  if(ret > 0 ){
    printf("father wait: %d. success,status exit code:%d, status signal:%d\n",ret,(status>>8)&0xFF,status&0x7F);
  }
  else{
    printf("father wait failed!\n");
  }
  sleep(5);
  return 0;
}
